#!/usr/bin/python
# -*- coding: utf-8 -*-




import sys, locale, os
import platform

cmd = ""

def show_help():
    print 'usage: cmd mark|list|restore path1 path2 path3 ...'
    sys.exit(0)    

if len(sys.argv) < 3:
    show_help()

cmd = sys.argv[1]
if (cmd == "mark" or cmd =="list" or cmd =="restore") == False:
    show_help()

filelist = sys.argv[2:]

#filelist = ["/home/zeus/data/algorithm","/home/zeus/data/book","/home/zeus/data1/sunjs","/home/zeus/data1/wy","/home/zeus/data1/songzq","/home/zeus/data1/LC"]


need_replace_sep = False
decode_for_path = "utf-8"
if platform.system() == "Windows":
    need_replace_sep = True
    decode_for_path = "gb2312"


def get_files_from_dir(_dir, exculdefiles=[".", ".."]):
    filelist=[]
    count = 1
    for root, dirs, files in os.walk(_dir):
        for name in files:
            if name not in exculdefiles:
                _path = root + "/" + name
                #_path = os.path.join(root,name)
                #_path = os.path.normpath(_path)
                # trick the root path maybe c:/dd\ss in windows
                global need_replace_sep
                if need_replace_sep:
                    _path = _path.replace("\\", "/")
                try:
                    filelist.append(_path.decode(decode_for_path))
                except UnicodeDecodeError, e:
                    print ("failed decode: " + _path + "\n")
                    continue
            count += 1
            #if count % 5000 == 0:
            #    my_log.debug("scan file: "+ str(count) + "\n")
            #if ProgressStatus.is_running() == False:
            #    return filelist
    return filelist




paths = []
for f in filelist:
    paths.extend(get_files_from_dir(f))


def is_nasca(f):
    fd = open(f,"r")
    r = fd.read(18)
    fd.close()
    if r == r"<## NASCA DRM FILE":
        return True
    else:
        return False


def check(change_name=False,restore=False):
    found_nasca_count = 0
    marked_nasca_count = 0
    all_count = 0

    for f in paths:
        n = os.path.splitext(f)
        if n[0].endswith(".nsc") is False:
            try:
                if is_nasca(f):
                    found_nasca_count += 1
                    if change_name:
                        nn = n[0] + ".nsc" + n[1]
                        print f + " ==> " + nn
                        os.rename(f, nn)
                    else:
                        print "NASCA FOUND:",f
            except:
                print "failed to check: "+f
                continue
        else:
            if restore == True:
                nn = n[0][:-4] + n[1]
                print f + " ==> " + nn
                os.rename(f, nn)
            marked_nasca_count += 1
        all_count += 1

    print "All checked:%d" % all_count
    print "Marked NASCA: %d" % marked_nasca_count
    print "Found NASCA: %d" % found_nasca_count

if cmd == "mark":
    check(True,False)
elif cmd =="restore":
    check(False,True)
else:
    check(False,False)


